<?php

namespace App\Common\Utils;

use DebugBar\Storage\StorageInterface;
use Illuminate\Support\Str;

class GelfStorage implements StorageInterface
{
    /**
     * {@inheritDoc}
     */
    public function save($id, $data)
    {
        // 由 DebugBar 启动记录 request 请求
        try {
            $requestInstance = app('request');
            $request = $requestInstance->all();
            $method = $requestInstance->method();
        } catch (\Exception $e) {
            $request = [];
            $method = 'GET';
        }

        try {
            if (count($data['queries']['statements'] ?? []) > 0) {
                foreach (array_chunk($data['queries']['statements'] ?? [], 30, true) as $chunk) {
                    \Log::info(json_encode([
                        'request' => $request,
                        'memory' => $data['memory'] ?? [],
                        'sql' => array_values(array_map(fn($sqlArr) => [($sqlArr['duration_str'] . '|' . Str::random(3)) => $sqlArr['sql']], $chunk)),
                    ], JSON_THROW_ON_ERROR),[
                        'duration' => round(($data['time']['duration'] ?? 0) * 1000, 2),
                        'method' => $method
                    ]);
                }
            } else {
                \Log::info(json_encode([
                    'request' => $request,
                    'memory' => $data['memory'] ?? [],
                    'sql' => [],
                ], JSON_THROW_ON_ERROR),[
                    'duration' => round(($data['time']['duration'] ?? 0) * 1000, 2),
                    'method' => $method,
                ]);
            }
        } catch (\Exception $e) {

        }
    }

    public function get($id)
    {
        return [];
    }

    public function find(array $filters = [], $max = 20, $offset = 0)
    {
        return [];
    }

    public function clear()
    {
    }
}
